﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Core.Metadata;
using Caliburn.PresentationFramework.ApplicationModel;
using Caliburn.PresentationFramework;
using XWord.Fundamental.Domain;
using Microsoft.Practices.ServiceLocation;
using System.Threading;
using XWord.Fundamental.Domain.Model;
using XWord.WPF.ApplicationFramework;
using Luna.WPF.ApplicationFramework;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows;
using XWord.WPF.ApplicationFramework.Threads;
using XWord.GUI.Presenters.Interface;
using XWord.Fundamental.Domain.Services;

namespace XWord.GUI.Presenters.Fundamental
{
    [Singleton("EtymaLibraryExplorerPresenter", typeof(IEtymaLibraryExplorerPresenter))]
    public class EtymaLibraryExplorerPresenter : DockingPresenter, IEtymaLibraryMasterScreen, IEtymaLibraryExplorerPresenter
    {
        private readonly IWindowManager _windowManager;
        private readonly IServiceLocator _serviceLocator;
        public EtymaLibraryExplorerPresenter(IServiceLocator entityFactory)
        {
            this.DisplayName = "词根";
            _serviceLocator = entityFactory;
            _windowManager = entityFactory.GetInstance<IWindowManager>();

        }

        protected override void OnInitialize()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) =>
            {
                IWordService wordSv = RemotingServiceFactory.GetWordService();
                AllEtymaLibraryList = wordSv.GetEtymaLibraryList().ToObservableCollection();
            }));

            base.OnInitialize();
        }

        #region EtymaList

        public IObservableCollection<EtymaMessage> _suffixEtymaList;
        public IObservableCollection<EtymaMessage> SuffixEtymaList
        {
            get { return _suffixEtymaList ?? (_suffixEtymaList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _suffixEtymaList = value;
                NotifyOfPropertyChange("SuffixEtymaList");
            }
        }

        public IObservableCollection<EtymaMessage> _prefixEtymaList;
        public IObservableCollection<EtymaMessage> PrefixEtymaList
        {
            get { return _prefixEtymaList ?? (_prefixEtymaList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _prefixEtymaList = value;
                NotifyOfPropertyChange("PrefixEtymaList");
            }
        }

        public IObservableCollection<EtymaMessage> _bindableprefixEtymaList;
        public IObservableCollection<EtymaMessage> BindablePrefixEtymaList
        {
            get { return _bindableprefixEtymaList ?? (_bindableprefixEtymaList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _bindableprefixEtymaList = value;
                NotifyOfPropertyChange("BindablePrefixEtymaList");
            }
        }

        public IObservableCollection<EtymaMessage> _etymaMessageList;
        public IObservableCollection<EtymaMessage> EtymaMessageList
        {
            get { return _etymaMessageList ?? (_etymaMessageList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _etymaMessageList = value;
                NotifyOfPropertyChange("EtymaMessageList");
            }
        }

        public IObservableCollection<EtymaLibrary> _alletymaLibraryList;
        public IObservableCollection<EtymaLibrary> AllEtymaLibraryList
        {
            get { return _alletymaLibraryList ?? (_etymaLibraryList = new BindableCollection<EtymaLibrary>()); }
            set
            {
                _alletymaLibraryList = value;
                NotifyOfPropertyChange("AllEtymaLibraryList");
            }
        }

        public IObservableCollection<EtymaLibrary> _etymaLibraryList;
        public IObservableCollection<EtymaLibrary> EtymaLibraryList
        {
            get { return _etymaLibraryList ?? (_etymaLibraryList = new BindableCollection<EtymaLibrary>()); }
            set
            {
                _etymaLibraryList = value;
                NotifyOfPropertyChange("EtymaLibraryList");
            }
        }

        #endregion

        private EtymaLibrary _selectedItem;
        public EtymaLibrary SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                NotifyOfPropertyChange("SelectedItem");
            }
        }

        #region edit

        public void OpenNewDialog()
        {
            OpenDialog(false);
        }

        public void OpenEditDialog()
        {
            OpenDialog(true);
        }

        private void OpenDialog(bool IsEdit)
        {
            //var presenter = _serviceLocator.GetInstance<EtymaLibraryEditPresenter>();
            //this.ActiveScreen = presenter;
            //if (IsEdit)
            //{
            //    presenter.Entity = SelectedItem;
            //    presenter.InitializeEditEntity();
            //}
            //else
            //{
            //    presenter.InitializeNewEntity();
            //}
            //_windowManager
            //    .ShowDialog(presenter, null, ExecuteShutdownModel);
        }

        public void Delete()
        {
            //Model.Delete(SelectedItem);
            EtymaLibraryList.Remove(SelectedItem);

        }

        #endregion

        public void Search(string text)
        {
            this.EtymaLibraryList = this.AllEtymaLibraryList.
                   Where(e => ParseText(e.Name).Any(m => m.Name.StartsWith(text))).Take(20).ToObservableCollection();
        }

        internal static IList<EtymaMessage> ParseText(string text)
        {
            var etymas = text.Split(new char[] { ',' });
            IList<EtymaMessage> messageList = new List<EtymaMessage>();
            for (int i = 0; i < etymas.Length; i++)
            {
                var message = new EtymaMessage();
                message.ParseEtyma(etymas[i].Trim());
                if (!string.IsNullOrEmpty(message.Name))
                {
                    messageList.Add(message);
                }
            }
            return messageList;
        }

        public void OpenEtymaDetail(EtymaLibrary etyma)
        {
            var webBrowserPresenter = _serviceLocator.GetInstance<WebBrowserPresenter>();
            webBrowserPresenter.DisplayName = etyma.Name;
            webBrowserPresenter.Source = new Uri("http://www.wordinfo.info/words/index/info/view_unit/" + etyma.WordIndex);
            webBrowserPresenter.Show();
        }

        private bool _isOpen;
        public bool IsOpen
        {
            get { return _isOpen; }
            set
            {
                _isOpen = value;
                NotifyOfPropertyChange("IsOpen");
            }
        }

        private string _etymaTip;
        public string EtymaTip
        {
            get { return _etymaTip; }
            set
            {
                _etymaTip = value;
                NotifyOfPropertyChange("EtymaTip");
            }
        }

        public void AddEtyma(IDataObject obj)
        {
            EtymaTip = "正在添加词根";
            IsOpen = true;

            var str = Convert.ToString(obj.GetData(DataFormats.UnicodeText));
            if (string.IsNullOrEmpty(str))
            {
                IsOpen = false;
                return;
            }
            if (AllEtymaLibraryList.Any(ee => ee.Name.Trim() == str.ToLower().Trim()))
            {
                EtymaTip = string.Format("{0}已经在列表中", str);
                GapDispatcherTimer.BeginInvoke(1, () =>
                {
                    IsOpen = false;
                });
            }
            else
            {
                EtymaLibrary el = new EtymaLibrary();
                el.Id = Guid.NewGuid();
                el.Name = str.ToLower().Trim();
                AllEtymaLibraryList.Add(el);
                EtymaLibraryList.Insert(0, el);
              
                EtymaTip = string.Format("{0}添加成功", str);
                GapDispatcherTimer.BeginInvoke(1, () =>
                {
                    IsOpen = false;
                });
            }
        }
    }
}
